package com.softa.common.sysconfig.config;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.corundumstudio.socketio.listener.DataListener;
import com.corundumstudio.socketio.listener.DisconnectListener;
import com.softa.common.constant.CacheConstants;
import com.softa.common.dto.MessageSiteDTO;
import com.softa.common.sysconfig.properties.MessageSiteProperties;
import com.softa.common.sysconfig.cache.ShiroCacheManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import java.io.InputStream;

/**
 * Created by yangl on 2018/9/2.
 */
@Configuration
@EnableConfigurationProperties({MessageSiteProperties.class})
@Import({CacheConfig.class})
public class MessageSiteConfig {

    private Logger logger = LoggerFactory.getLogger(MessageSiteConfig.class);

    @Bean
    public SocketIOServer socketIOServer(MessageSiteProperties messageSiteProperties, ShiroCacheManager cacheManager){
        com.corundumstudio.socketio.Configuration configuration = new com.corundumstudio.socketio.Configuration();
       //ssl
        if(StringUtils.isNotBlank(messageSiteProperties.getKeystore()) &&
                StringUtils.isNotBlank(messageSiteProperties.getKeystorepwd())) {
            configuration.setKeyStorePassword(messageSiteProperties.getKeystorepwd());
            InputStream stream = getClass().getResourceAsStream(messageSiteProperties.getKeystore());
            configuration.setKeyStore(stream);
        }
        configuration.setPort(messageSiteProperties.getPort());
        configuration.setHostname(messageSiteProperties.getHostname());
        SocketIOServer socketIOServer = new SocketIOServer(configuration);

        Cache cache = cacheManager.getCache(CacheConstants.MESSAGE_SITE_CACHE);

        //客户端连接监听器
        socketIOServer.addConnectListener(new ConnectListener() {
            @Override
            public void onConnect(SocketIOClient client) {
                logger.debug("client connect to socket-io with session : {}",client.getSessionId().toString());
            }
        });

        //接收客户端数据
        socketIOServer.addEventListener(messageSiteProperties.getChanel(), MessageSiteDTO.class, new DataListener<MessageSiteDTO>() {
            @Override
            public void onData(SocketIOClient client, MessageSiteDTO data, AckRequest ackRequest) {
                cache.put(data.getUserId(), client.getSessionId().toString());
                cache.put(client.getSessionId().toString(), data.getUserId());
            }
        });

        //客户端断开连接
        socketIOServer.addDisconnectListener(new DisconnectListener() {
            @Override
            public void onDisconnect(SocketIOClient client) {
                String userId = (String) cache.get(client.getSessionId().toString());
                cache.remove(client.getSessionId().toString());
                cache.remove(userId);
            }
        });

        socketIOServer.startAsync();

        return socketIOServer;
    }

}
